package com.zenithmind.exam.controller;

import com.zenithmind.common.result.Result;
import com.zenithmind.exam.pojo.entity.ExamStatistics;
import com.zenithmind.exam.service.ExamStatisticsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.constraints.NotBlank;
import java.math.BigDecimal;
import java.util.List;

/**
 * 考试统计控制器
 * 
 * @author ZenithMind
 * @since 2024-07-01
 */
@Slf4j
@RestController
@RequestMapping("/api/exam/statistics")
@RequiredArgsConstructor
@Validated
@Tag(name = "考试统计管理", description = "考试统计分析相关操作")
public class ExamStatisticsController {

    private final ExamStatisticsService examStatisticsService;

    @PostMapping("/exam/{examId}/update")
    @Operation(summary = "更新考试统计", description = "更新指定考试的统计信息")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Boolean> updateExamStatistics(
            @Parameter(description = "考试ID") @PathVariable @NotBlank String examId) {
        boolean result = examStatisticsService.updateExamStatistics(examId);
        return Result.success(result);
    }

    @GetMapping("/exam/{examId}")
    @Operation(summary = "获取考试统计", description = "获取指定考试的统计信息")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<ExamStatistics> getExamStatistics(
            @Parameter(description = "考试ID") @PathVariable @NotBlank String examId) {
        ExamStatistics statistics = examStatisticsService.getExamStatistics(examId);
        return Result.success(statistics);
    }

    @GetMapping("/hot")
    @Operation(summary = "获取热门考试统计", description = "获取热门考试的统计信息")
    public Result<List<ExamStatistics>> getHotExamStatistics(
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "10") Integer limit) {
        List<ExamStatistics> statistics = examStatisticsService.getHotExamStatistics(limit);
        return Result.success(statistics);
    }

    @GetMapping("/high-pass-rate")
    @Operation(summary = "获取高通过率考试", description = "获取高通过率考试的统计信息")
    public Result<List<ExamStatistics>> getHighPassRateExams(
            @Parameter(description = "最低通过率") @RequestParam(defaultValue = "80") BigDecimal minPassRate,
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "10") Integer limit) {
        List<ExamStatistics> statistics = examStatisticsService.getHighPassRateExams(minPassRate, limit);
        return Result.success(statistics);
    }

    @GetMapping("/low-pass-rate")
    @Operation(summary = "获取低通过率考试", description = "获取低通过率考试的统计信息")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<List<ExamStatistics>> getLowPassRateExams(
            @Parameter(description = "最高通过率") @RequestParam(defaultValue = "50") BigDecimal maxPassRate,
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "10") Integer limit) {
        List<ExamStatistics> statistics = examStatisticsService.getLowPassRateExams(maxPassRate, limit);
        return Result.success(statistics);
    }

    @GetMapping("/overall")
    @Operation(summary = "获取总体统计", description = "获取系统总体统计信息")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<ExamStatistics> getOverallStatistics() {
        ExamStatistics statistics = examStatisticsService.getOverallStatistics();
        return Result.success(statistics);
    }

    @GetMapping("/score-range/count")
    @Operation(summary = "按分数范围统计", description = "根据平均分范围统计考试数量")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Integer> countByAvgScoreRange(
            @Parameter(description = "最低平均分") @RequestParam BigDecimal minAvgScore,
            @Parameter(description = "最高平均分") @RequestParam BigDecimal maxAvgScore) {
        Integer count = examStatisticsService.countByAvgScoreRange(minAvgScore, maxAvgScore);
        return Result.success(count);
    }

    @GetMapping("/recent-updated")
    @Operation(summary = "获取最近更新的统计", description = "获取最近更新的统计信息")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<List<ExamStatistics>> getRecentUpdatedStatistics(
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "20") Integer limit) {
        List<ExamStatistics> statistics = examStatisticsService.getRecentUpdatedStatistics(limit);
        return Result.success(statistics);
    }

    @GetMapping("/score-range")
    @Operation(summary = "获取分数段统计", description = "获取各分数段的统计信息")
    public Result<List<ExamStatistics>> getScoreRangeStatistics() {
        List<ExamStatistics> statistics = examStatisticsService.getScoreRangeStatistics();
        return Result.success(statistics);
    }

    @PostMapping("/batch-update")
    @Operation(summary = "批量更新统计", description = "批量更新需要更新的考试统计")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Boolean> batchUpdateStatistics() {
        boolean result = examStatisticsService.batchUpdateStatistics();
        return Result.success(result);
    }

    @GetMapping("/exam/{examId}/report")
    @Operation(summary = "生成统计报告", description = "生成指定考试的详细统计报告")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<ExamStatistics> generateStatisticsReport(
            @Parameter(description = "考试ID") @PathVariable @NotBlank String examId) {
        ExamStatistics report = examStatisticsService.generateStatisticsReport(examId);
        return Result.success(report);
    }

    @DeleteMapping("/exam/{examId}")
    @Operation(summary = "删除考试统计", description = "删除指定考试的统计信息")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Boolean> deleteExamStatistics(
            @Parameter(description = "考试ID") @PathVariable @NotBlank String examId) {
        boolean result = examStatisticsService.deleteExamStatistics(examId);
        return Result.success(result);
    }

    @PostMapping("/recalculate-all")
    @Operation(summary = "重新计算所有统计", description = "重新计算所有考试的统计信息")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Boolean> recalculateAllStatistics() {
        boolean result = examStatisticsService.recalculateAllStatistics();
        return Result.success(result);
    }

    @GetMapping("/exam/{examId}/difficulty-analysis")
    @Operation(summary = "获取难度分析", description = "获取指定考试的难度分析")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<String> getDifficultyAnalysis(
            @Parameter(description = "考试ID") @PathVariable @NotBlank String examId) {
        String analysis = examStatisticsService.getDifficultyAnalysis(examId);
        return Result.success(analysis);
    }

    @GetMapping("/exam/{examId}/question-analysis")
    @Operation(summary = "获取题目分析", description = "获取指定考试的题目分析")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<String> getQuestionAnalysis(
            @Parameter(description = "考试ID") @PathVariable @NotBlank String examId) {
        String analysis = examStatisticsService.getQuestionAnalysis(examId);
        return Result.success(analysis);
    }

    @GetMapping("/exam/{examId}/score-distribution")
    @Operation(summary = "获取分数分布", description = "获取指定考试的分数分布")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<String> getScoreDistribution(
            @Parameter(description = "考试ID") @PathVariable @NotBlank String examId) {
        String distribution = examStatisticsService.getScoreDistribution(examId);
        return Result.success(distribution);
    }
}
